package cn.com.lms.business.exam.service;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.exam.persistence.entity.Exercise;
import cn.com.lms.business.exam.persistence.entity.ExerciseEmployee;
import cn.com.lms.business.exam.persistence.entity.QuestionSubjectOption;
import cn.com.lms.business.exam.persistence.repository.ExerciseEmployeeRepository;
import cn.com.lms.business.exam.web.vo.QuestionSubjectExportVO;

import com.bnzj.core.export.Column;


import com.bnzj.core.persistence.BaseService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Service
public class ExerciseEmployeeService extends BaseService<ExerciseEmployeeRepository, ExerciseEmployee,Long> {


    public List<Map> findEmployeeByExerciseId(Long exerciseId){
        return  repository.findEmployeeByExerciseId(exerciseId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchSave(Exercise exercise, List<ExerciseEmployee> exerciseEmployeeList){

        if (!CollectionUtils.isEmpty(exerciseEmployeeList)) {
            List<ExerciseEmployee> exerciseEmployees = exerciseEmployeeList.stream().map(exerciseEmployee -> {
                    exerciseEmployee.setExerciseId(exercise.getId());
                    exerciseEmployee.setCreator(exercise.getCreator());
                    exerciseEmployee.setCreateTime(exercise.getCreateTime());
                    exerciseEmployee.setCreatorName(exercise.getCreatorName());
                    exerciseEmployee.setIsDelete(false);
                    return exerciseEmployee;
            }).collect(Collectors.toList());
            super.saveAll(exerciseEmployees);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int  deleteByExerciseId(Long exerciseId){
      return   repository.deleteByExerciseId(exerciseId);
    }

    public HSSFWorkbook exportExerciseEmployeeListById(Long exerciseId, List<Map> employeeMaplist) {
        List<String> firstRowFildList = Arrays.asList("姓名", "部门", "已做题数","答对题数","完成率(%)","正确率(%)","最后练习时间");
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        String sheetName="Sheet0";
        List<Column> columnList = new CopyOnWriteArrayList<>();
        firstRowFildList.stream().forEach(str -> {
            Column column = new Column(str, str, firstRowFildList.indexOf(str));
            columnList.add(column);
        });
        this.exportExcel(hssfWorkbook, sheetName, employeeMaplist, columnList);
        return  hssfWorkbook;
    }

    public  void exportExcel(HSSFWorkbook workbook,String sheetName,List<Map> dataList,List<Column> columns){
        try {
            // 声明一个工作薄
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(sheetName);
            // 设置密码保护表格不可编辑
            // sheet.protectSheet("12345678");
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth(20);
            // 生成一个样式
            HSSFCellStyle columnStyle = workbook.createCellStyle();
            // 生成一个字体
            HSSFFont columnFont = workbook.createFont();

            columnFont.setFontHeightInPoints((short) 9);
            columnFont.setBold(false);
            // 把字体应用到当前的样式 206,255,206
//            HSSFPalette customPalette = workbook.getCustomPalette();
//            HSSFColor hssfColor=customPalette.addColor((byte)206,(byte)255,(byte)206);
            columnStyle.setFont(columnFont);

            columnStyle.setFillBackgroundColor(IndexedColors.LIME.getIndex());
            columnStyle.setFillPattern(FillPatternType.NO_FILL);
            columnStyle.setAlignment(HorizontalAlignment.CENTER);
            columnStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 生成并设置另一个样式
            HSSFCellStyle dataStyle = workbook.createCellStyle();
            // 生成另一个字体
            HSSFFont dataFont = workbook.createFont();
            dataFont.setBold(false);
            // 把字体应用到当前的样式
            dataStyle.setFont(dataFont);


            HSSFFont font3 = workbook.createFont();
            // 声明一个画图的顶级管理器
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            // 产生表格填写须知
            // 生成一个样式
            HSSFCellStyle noticeStyle = workbook.createCellStyle();
            // 生成一个字体
            HSSFFont noticeFont = workbook.createFont();
            noticeFont.setFontHeightInPoints((short) 14);
            noticeFont.setBold(false);
            noticeFont.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
            // 把字体应用到当前的样式
            noticeStyle.setFont(noticeFont);
            HSSFRow noticeRow = sheet.createRow(0);
            HSSFCell noticeCell = noticeRow.createCell(0);
            noticeStyle.setWrapText(true);
            noticeCell.setCellStyle(noticeStyle);
            HSSFRichTextString noticetext = new HSSFRichTextString("测试练习");
            noticeCell.setCellValue(noticetext);
            noticeRow.setHeightInPoints(110);
            // 合并单元格
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
            // 产生表格标题行
            HSSFRow row = sheet.createRow(1);
            for (int i = 0; i < columns.size(); i++) {
                Column column = columns.get(i);
                if (column.isVisible()) {
                    sheet.setColumnWidth(i, 100 * column.getWidth());
                    HSSFCell cell = row.createCell(i);
                    cell.setCellStyle(columnStyle);
                    HSSFRichTextString text = new HSSFRichTextString(column.getTitle());
                    cell.setCellValue(text);


                }
            }

            for (int i = 0; i < dataList.size(); i++) {
                row = sheet.createRow(i + 2);
                Map map = dataList.get(i);
                for (int j = 0; j < columns.size(); j++) {
                    Column column = columns.get(j);
                    if (column.isVisible()) {
                        sheet.setColumnWidth(j, 100 * column.getWidth());
                        HSSFCell cell = row.createCell(j);
                        cell.setCellStyle(columnStyle);
                        HSSFRichTextString text = null;
                        if (j == 0) {
                            // 姓名
                            text = new HSSFRichTextString((String)map.get("cname"));
                        } else if (j == 1) {
                            // 部门
                            text = new HSSFRichTextString((String)map.get("department"));
                        } else if (j == 2) {
                            // 已做题数
                            text = new HSSFRichTextString((String)map.get("finishSubjectCount"));
                        } else if(j==3) {
                            // 答对题数
                            text = new HSSFRichTextString((String)map.get("correctCount"));
                        }else if (j == 1) {
                            // 完成率
                            text = new HSSFRichTextString((String)map.get("finishRate"));
                        }else if (j == 1) {
                            // 正确率
                            text = new HSSFRichTextString((String)map.get("correctRate"));
                        }else{
                           //  最后练习时间
                            text = new HSSFRichTextString((String)map.get("lastExerciseTime"));
                        }
                        cell.setCellValue(text);

                    }
                }
            }
        } catch (Exception e) {
//            log.error("", e);
        }
    }
}
